package top.ffhome.system.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import top.ffhome.common.audit.AuditService;
import top.ffhome.common.exception.BusinessException;
import top.ffhome.common.service.impl.BaseServiceImpl;
import top.ffhome.system.constant.SysConstants;
import top.ffhome.system.entity.SysRole;
import top.ffhome.system.mapper.SysRoleMapper;
import top.ffhome.system.service.SysRoleService;

@Service
@AuditService(entity = SysRole.class)
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole, SysRoleMapper> implements SysRoleService {
	@Override
	protected void afterSave(SysRole entity) {
		saveMenuRelation(entity);
		super.afterSave(entity);
	}

	@Override
	protected void beforeDelete(List<Long> ids) {
		for (Long id : ids) {
			if (mapper.checkUsed(id) > 0) {
				throw new BusinessException("该角色已经被人员使用，请取消人员该角色后再删除");
			}
		}
		super.beforeDelete(ids);
	}

	@Override
	protected void afterDelete(List<Long> ids) {
		for (Long id : ids) {
			mapper.deleteMenuRelation(id);
		}
		super.afterDelete(ids);
	}

	/**
	 * 保存角色与菜单关联处理
	 * 
	 * @param entity
	 */
	private void saveMenuRelation(SysRole entity) {
		if (entity.getMenuIds() == null || entity.getMenuIds().size() == 0) {
			return;
		}
		mapper.deleteMenuRelation(entity.getId());
		mapper.insertMenuRelation(entity.getId(), entity.getMenuIds());
	}

	@Override
	@CacheEvict(value = { "role_getAll", "user_selectByAccount", "user_selectPermsByAccount" }, allEntries = true)
	public void clearCache() {
	}

	@Override
	@Cacheable(value = "role_getAll", unless = "#result == null || #result.size() == 0")
	public List<SysRole> getAll() {
		SysRole dto = new SysRole();
		dto.setStatus(SysConstants.NORMAL);
		dto.getParams().put("fields", "r.id,r.name");
		dto.getParams().put("orderBy", "sort");
		return mapper.select(dto);
	}

	@Override
	public Set<Long> selectMenusByRoleId(Long roleId) {
		return mapper.selectMenusByRoleId(roleId);
	}
}
